
class ContentInsertionThing < Thing
  def creator e
    "-- here will be the content of your page --"
  end

  def render e
    e.page.content || '-- no content here --'
  end
end

class SidebarContainer < ContainerThing
  def thingswecanadd
    [TextThing, MenuThing, ImageThing]
  end
end

class ContentContainer < ContainerThing
  def thingswecanadd
    [TextThing, ContentInsertionThing]
  end
end


class FooterContainer < ContainerThing
  def wrap_render e
    '<br style="clear:both">'+super
  end

  def thingswecanadd
    [TextThing, HtmlCode, TitleThing, MenuThing]
  end
end


class HeaderContainer < ContainerThing
  def thingswecanadd
    [TextThing, HtmlCode, TitleThing, MenuThing]
  end
end



class PageMeta < FieldGroup
  def initialize *a
    can_add_more false
    super
  end

  field :title, StringField.new.tap {|field|
    field.child = TitleThing.new
  }
  field :place, PlaceField.new.tap {|field|
    field.child = NodeChooserThing.new
  }
  field :apply_on_children, BooleanField.new.tap {|field|
    field.child =  CheckBoxThing.new
  }

  attr_accessor :name

  def render e
    ''
  end
end



class PageThing < ContentWithFields

  attr_accessor :content, :document, :body, :head

  field :meta, PageMeta.new

=begin
  field :title, ContentTemplate::StringField
  field :place, ContentTemplate::PlaceField
  field :apply_on_children, ContentTemplate::BooleanField
=end

  def initialize
    super
    can_add_more false
  end

  def self.create_default
    p = new
    p.default_template
    p
  end

  def default_template
    #add TitleThing.new
    add HeaderContainer.new.tap { |c|
      c.add title = TitleThing.new
      title.content = "My Site"
    }
    add SidebarContainer.new.tap { |c|
      c.add MenuThing.new
    }
    add ContentContainer.new.tap { |c|
      c.add ContentInsertionThing.new
    }
    add FooterContainer.new
  end
  

  def document
    @document ||= setup_document
  end
  
  def setup_document
    doc = Element.new(nil)
    doc << '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+ "\n" +
          '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs">' + "\n"
    doc
  end

  def body
    @body ||= Element.new(:body)
  end


  def head
    @head ||= setup_head
  end

  def setup_head
    Element.new(:head).tap { |head|
      head << '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'      
      head << CssFile.all.map { |css|
        '<link rel="stylesheet" type="text/css" href="/css/'+css.identity+'/'+css.version+'">'
      }.join("")      
    }
  end


  def wrap_render e
    e.data['page'] = self
    self.head = (@original_head ||= self.head).clone
    self.document = (@original_doc ||= self.document).clone
    self.body = (@original_body ||= self.body).clone
    self.body << super
    document << head
    document << body
  end

  def thingswecanadd
    [TextThing, ContainerThing]
  end

end
